<template>
  <div class="app-container">
    <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="toolbarButtonClickEvent">
      <template #clock="{ row }">
        <vxe-switch v-model="row.isLocked" size="mini" open-label="是" close-label="否" @change="updateLocked(row)">
        </vxe-switch>
      </template>
    </y-table>
    <y-form-dialog :title="formConfig.title" ref="dialogFormRef" :form-options="formConfig"
      @confirm="confirmForm"></y-form-dialog>
    <y-form-dialog :title="passwordFormConfig.title" ref="dialogPasswordRef" :form-options="passwordFormConfig"
      @confirm="editPasswordSubmit"></y-form-dialog>
  </div>
</template>

<script>

import {
  getUserList, resetErrorNum, setIsLocked, deleteUser, updatePassword, updateUser, addUser, getUserRoleList
} from '@/api/sys/user' // 接口

import listMixin from '@/mixins/listMixin'

export default {
  mixins: [listMixin],
  data() {
    return {
      // 表格配置
      listOptions: {

        // 默认查询数据
        defaultQueryData: {
          // form
          form: {},
          // 分页
          page: {
            pageSize: 50
          },
          // 其他查询参数
          params: {}
        },
        // 获取数据方法
        dataMethod: getUserList,
        // 表格配置
        tableOptions: {
          height: '',
          rowConfig: {
            keyField: 'tid'
          },
          toolbarConfig: {
            // 按钮组
            buttons: [
              { name: '新增用户', code: 'add', status: 'primary', icon: 'vxe-icon-add' },
            ],
            // 工具栏
            tools: [
              // { type: 'button', code: 'DivCode', icon: 'vxe-icon-edit', circle: true },
            ]
          },
          // 表格列
          columns: [
            { type: 'seq', width: 48, align: 'center', fixed: 'left' },
            { field: 'passId', width: 150, title: '账号' },
            { field: 'userName', title: '姓名' },
            { field: 'userType', width: 150, title: '用户类别', dictName: 'frame_user_type' },
            { field: 'mobilePhone', width: 150, title: '移动电话' },
            { field: 'lastLoginTime', width: 180, title: '最后登录时间' },
            { field: 'isLocked', width: 150, title: '是否锁定', slots: { default: 'clock' } },
            {
              title: '操作',
              width: 130,
              cellRender: {
                name: 'buttons',
                options: [
                  { content: '修改', name: 'edit' },
                  {
                    content: '更多', dropdowns: [
                      { content: '重置', name: 'reset' },
                      { content: '修改密码', name: 'editPassword' },
                      { content: '删除', name: 'delete' }
                    ]
                  }
                ],
                events: { click: ({ name, row }) => this.controlSwitch(name, row) }
              }
            }
          ]
        },
        // 查询配置
        formOptions: {
          items: [
            {
              field: 'userType', title: '用户类别',
              itemRender: {
                name: 'ZSelect',
                props: {
                  dictCode: 'frame_user_type'
                }
              }
            },
            {
              field: 'keywords', title: '姓名/工号',
              itemRender: { name: 'VxeInput' },
              rules: [{ max: 20, message: '长度不能超过20个字符' }]
            }
          ]
        }
      },
      formConfig: {
        title: '用户信息',
        titleWidth: 140,
        mounted: ({ data }) => {
          this.formData = data
        },
        items: [
          {
            field: 'userName', title: '姓名', required: true,
            itemRender: {
              name: 'VxeInput',
              props: {
                disabled: false
              }
            },
            rules: [{ max: 50, message: '长度不能超过50个字符' }]
          },
          {
            field: 'passId', title: '用户账号', required: true,
            itemRender: {
              name: 'VxeInput',
              props: {
                disabled: false
              }
            },
            rules: [{ max: 50, message: '长度不能超过50个字符' }]
          },
          {
            field: 'password', title: '用户密码',
            visibleMethod: ({ data }) => !data.userId,
            itemRender: {
              name: 'VxeInput',
              props: {
                type: 'password'
              }
            },
            rules: [
              {
                pattern: /((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))(?!^.*[\u4E00-\u9FA5].*$)^\S{6,16}$/,
                message: '请设置正确的密码格式'
              }
            ]
          },
          {
            field: 'mobilePhone', title: '移动电话',
            itemRender: { name: 'VxeInput' },
            rules: [
              { required: true },
              { type: 'string', pattern: '^1[3-9]\\d{9}$', message: '请输入11位的手机号码', trigger: 'blur' }
            ]
          },
          {
            field: 'email', title: '电子邮箱', itemRender: { name: 'VxeInput' },
            rules: [
              { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入正确的邮箱格式', trigger: 'blur' }]
          },
          {
            field: 'qq', title: 'QQ号码',
            itemRender: {
              name: 'VxeInput'
            },
            rules: [{ max: 20, message: '长度不能超过20个字符' }]
          },
          {
            field: 'userType', title: '用户类别',
            itemRender: {
              name: 'ZSelect',
              props: {
                disabled: true,
                dictCode: 'frame_user_type'
              }
            }
          },
          {
            field: 'roles',
            title: '用户角色',
            itemRender: {
              name: 'ZSelect',
              props: {
                type: 'checkbox',
                dictCode: 'frame_role'
              },
              events: {
                change: (data, detail) => {
                  if (detail && detail.length > 0) {
                    this.$set(this.formData, 'userType', detail[0].details.userType)
                  }
                }
              }
            }
          }
        ]
      },
      passwordFormConfig: {
        title: '修改密码',
        titleWidth: 140,
        items: [
          {
            field: 'password', title: '用户密码',
            itemRender: {
              name: 'VxeInput',
              props: {
                type: 'password'
              }
            },
            rules: [
              {
                pattern: /((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))(?!^.*[\u4E00-\u9FA5].*$)^\S{6,16}$/,
                message: '请设置正确的密码格式'
              }
            ]
          }
        ]
      }
    }
  },
  /**
   * 组件挂载时异步执行的方法
   */
  async mounted() {
    // 动态设置查询参数
    // 此处的目的是根据某些条件或逻辑动态地设置组件的查询参数，以便在加载数据前做好准备
    await this.setFormQuery()

    // 加载数据
    // 通过refs引用调用loadData方法来加载数据
    this.$refs.gridRef.loadData()
  },
  methods: {
    /**
     * 工具栏按钮点击事件处理函数
     * @param {Object} event - 事件对象，包含按钮代码
     * 该函数根据点击的工具栏按钮代码，执行不同的操作
     */
    toolbarButtonClickEvent({ code }) {
      switch (code) {
        case 'add':
          // 执行添加操作，打开表单对话框
          //开启禁用
          this.formConfig.items.filter((item) => ['passId', 'userName'].includes(item.field))
            .forEach(item => {
              item.itemRender.props.disabled = false
            })
          this.openFormDialog({ row: null, refName: 'dialogFormRef' })
          break
        default:
          break
      }
    },
    controlSwitch(name, row) {
      switch (name) {
        case 'edit':
          //开启禁用
          this.formConfig.items.filter((item) => ['passId', 'userName'].includes(item.field))
            .forEach(item => {
              item.itemRender.props.disabled = true
            })
          getUserRoleList(row.passId).then(res => {
            if (res.status) {
              this.$set(row, 'roles', [])
              res.data.forEach(item => {
                row.roles.push(item.roleId)
              })
              this.openFormDialog({ row, refName: 'dialogFormRef' })
            }
          })
          break
        case 'delete':
          this.deleteRow({ row, deleteMethod: (row) => this.deleteById(row) })
          break
        case 'editPassword':
          this.openFormDialog({ row, refName: 'dialogPasswordRef' })
          break
        case 'reset':
          this.resetErrorNum(row)
          break
        default:
          break
      }
    },

    //修改密码弹窗提交
    async editPasswordSubmit(form) {
      return new Promise((resolve, reject) => {
        updatePassword(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    //提交表单
    async confirmForm(form) {
      return new Promise((resolve, reject) => {
        this.saveOrUpdate(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    // 保存或修改
    saveOrUpdate(form) {
      if (form.tid) {
        return updateUser(form)
      } else {
        return addUser(form)
      }
    },
    // 修改
    updateLocked(row) {
      setIsLocked(row.userId, row.isLocked).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    resetErrorNum(row) {
      this.$confirm('确定要重置该用户的错误次数吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetErrorNum(row.userId).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
          }
        })
      })
    },
    // 删除
    deleteById(row) {
      deleteUser(row.userId, row.passId).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    async setFormQuery() {
      // this.listOptions.defaultQueryData.form.pageSize = 50
      // this.listOptions.defaultQueryData.form.pageNum = 1
      // this.dictCampusList = await this.getDictItems("campus_list");
      // this.dictCollegeList = await this.getDictItems("college_list");
    },
    getRadioRow() {
      return this.$refs.gridRef.$refs.gridRef.getRadioRecord()
    },
    getCheckboxRow() {
      return this.$refs.gridRef.$refs.gridRef.getCheckboxRecords()
    }
  }
}
</script>

<style lang="scss" scoped></style>
